<template>
  <div class="border-normal">
    <div class="border-normal" style="width: 800px; height: 450px; overflow-y:auto;" id="chat">
      <div class="add-border" style="height: 50px;" v-for="(c, i) in session.content" :key="i">
        <div
          class="add-border"
          style="height: 44px; margin: 2px; float: right;"
          v-if="c.isSend == 1"
        >
          <div style="margin-right: 20px;">
            <span style="float: right; font-weight: bold;">我</span>
          </div>
          <span style="margin: auto; float: right; margin-right: 30px;">{{c.content}}</span>
        </div>
        <div
          class="add-border"
          style="height: 44px; margin: 2px; float: left;"
          v-if="c.isSend == 0"
        >
          <div style="margin-left: 20px;">
            <span style="float: left; font-weight: bold;">{{session.targetName}}</span>
          </div>
          <span style="margin: auto; float: left; margin-left: 30px;">{{c.content}}</span>
        </div>
      </div>
    </div>
    <div class="add-border" style="height: 140px;" v-show="showInput == 1">
      <el-input
        v-model="input"
        placeholder="请输入内容，回车发送"
        type="textarea"
        :rows="6"
        resize="none"
        style="margin: auto;"
        @keyup.enter.native="sendMessage()"
      ></el-input>
    </div>
  </div>
</template>

<script>
export default {
  name: "MessageSession",
  data() {
    return {
      showInput: 0,
      input: "",
      session: {},
    };
  },
  methods: {
    init(session) {
      this.session = session;
      this.showInput = 1;
    },
    sendMessage() {
      var url = process.env.URL_HEAD + "/api/message/message/save";
      var content = this.input.trim();
      this.input = "";

      if (content.length == 0) return;

      var message = {
        messageId: 100,
        sendId: this.session.userId,
        sendType: "user",
        receiveId: this.session.targetId,
        receiveType: this.session.targetType,
        content: content,
        sendTime: new Date(),
      };

      this.$http.post(url, message).then(
        (response) => {
          this.$message.success("已发送！");

          this.updateSession(
            this.session.targetType,
            this.session.targetId,
            1,
            content
          );
        },
        (response) => {
          this.$message.error("系统异常，请重试");
        }
      );
    },
    updateSession(targetType, targetId, isSend, content) {
      this.$emit("updateSession", targetType, targetId, isSend, content);
    },
  },
  updated() {
    var msg = document.getElementById("chat"); // 获取对象
    msg.scrollTop = msg.scrollHeight; // 滚动高度
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.add-border {
  border: 1px solid #ffffff;
}
.border-normal {
  border: 1px solid #bbbbbb;
}
</style>
